package com.bskms.controller;

import com.bskms.enums.LoginTypeEnum;
import com.bskms.mapper.UserMapper;
import com.bskms.model.*;
import com.bskms.service.UserAService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * 登录和注册的控制器
 */
@Controller
public class LoginAController {

  private Logger logger = LoggerFactory.getLogger(this.getClass());
  @Autowired
  private UserAService userAService; //用户service类
  @Autowired
  private SimpMessagingTemplate messagingTemplate; //消息模板
  @Autowired
  private ParticipantRepository participantRepository; //在线用户存储

  @Autowired
  private UserMapper userMapper;

  private static final String SUBSCRIBE_LOGIN_URI = "/topic/login"; //订阅的登录地址

  /**
   * 反馈前端ajax登录的消息
   */
  @RequestMapping(value = "/reply/login", method = RequestMethod.POST)
  @ResponseBody
  public ReplyLoginMessage replayLoginMessage(@RequestBody User user) {
    if (user.getName() == null || user.getName().trim().equals("")
        || user.getPassword() == null || user.getPassword().equals("")) {
      return new ReplyLoginMessage(false, ReplyLoginMessage.USER_NAME_OR_PASSWORD_NULL);
    }
    boolean isExist = userAService.isExistUser(user.getName());
    if (!isExist) {
      return new ReplyLoginMessage(false, ReplyLoginMessage.USER_NAME_NOT_EXIST);
    }
    User res = userAService.validateUserPassword(user.getName(), user.getPassword());
    if (res == null) {
      return new ReplyLoginMessage(false, ReplyLoginMessage.USER_PASSWORD_WRONG);
    }
    return new ReplyLoginMessage(true);
  }

  /**
   * 反馈前端ajax注册的消息
   */
  @RequestMapping(value = "/reply/regist", method = RequestMethod.POST)
  @ResponseBody
  public ReplyRegistMessage replyRegistMessage(@RequestBody User user) {
    boolean isExist = userAService.isExistUser(user.getName());
    if (isExist) {
      return new ReplyRegistMessage(false, ReplyRegistMessage.USER_NAME_EXIST);
    }
    if (user.getPassword() != null) {
      userAService.insertUser(user.getName(), user.getPassword());
    }
    return new ReplyRegistMessage(true);
  }

  /**
   * 登录进入聊天室
   */
  @RequestMapping(value = "/chat", method = RequestMethod.POST)
  public String loginIntoChatRoom(User user, HttpServletRequest request, Model model) {
    HttpSession session = request.getSession();

    String userName = String.valueOf(session.getAttribute("LoginUser"));
    user.setLoginDate(new Date());
    //设空防止泄露给其他用户
    user.setPassword(null);
    if (Objects.nonNull(userName)) {
      model.addAttribute("userName", user.getName());
      session.setAttribute("user", user);
    } else {
      user = userAService.validateUserPassword(user.getName(), user.getPassword());
      if (user == null) {
        return "login";
      }
    }

    model.addAttribute("userName", user.getName());
    session.setAttribute("user", user);
    //保存登陆信息
    LoginInfoDo loginInfo = LoginInfoDo.builder().userId(user.getId()).userName(user.getName()).
        status(LoginTypeEnum.LOGIN.getCode()).createTime(new Date()).build();
    userAService.addUserLoginInfo(loginInfo);
   /*     List<Message> messageList = userMapper.listMessageLimit();
        messagingTemplate.send();
*/
    messagingTemplate.convertAndSend(SUBSCRIBE_LOGIN_URI, user);

    participantRepository.add(user.getName(), user);
    logger.info(user.getLoginDate() + ", " + user.getName() + " login.");
    return "chatroom";
  }


  /**
   * 登录进入聊天室
   */
  @RequestMapping(value = "/indexChat", method = RequestMethod.GET)
  public String indexChat(HttpServletRequest request, Model model) {
    HttpSession session = request.getSession();
    User user = new User();
    String userName = String.valueOf(session.getAttribute("LoginUser"));
    user.setLoginDate(new Date());
    //设空防止泄露给其他用户
    user.setPassword(null);
    if ("null".equals(userName) || userName == null || "".equals(userName)) {
      return "login";

    }
    user.setName(userName);
    model.addAttribute("userName", user.getName());
    session.setAttribute("user", user);
    //保存登陆信息
    LoginInfoDo loginInfo = LoginInfoDo.builder().userId(user.getId()).userName(user.getName()).
        status(LoginTypeEnum.LOGIN.getCode()).createTime(new Date()).build();
    userAService.addUserLoginInfo(loginInfo);
    messagingTemplate.convertAndSend(SUBSCRIBE_LOGIN_URI, user);
    logger.info(user.getLoginDate() + ", " + user.getName() + " login.");

    model.addAttribute("userName", user.getName());
    session.setAttribute("user", user);
    participantRepository.add(user.getName(), user);
    return "chatroom";
  }


  /**
   * 登录页面
   */
  @RequestMapping(value = "/chatApply", method = RequestMethod.GET)
  public String index() {
    return "indexA";
  }

  /**
   * 返回当前在线人数
   */
  @SubscribeMapping("/chat/participants")
  public Long getActiveUserNumber() {
    return Long.valueOf(participantRepository.getActiveSessions().values().size());
  }

  @GetMapping("/html")
  public void ddd(HttpServletResponse response,
      HttpServletRequest request) throws IOException {
    StringBuffer requestURL = request.getRequestURL();
    response.sendRedirect("/htm/pages/a.html");
  }
}
